<template>
  <div class="wrapper">
    <div class="login-box">
      <div class="logo">
        <img src="../../assets/CUG_Logo-1.svg" height="120px" alt="" />
      </div>
      <!-- <h3 class="title">登录界面</h3> -->
      <!-- <div>{{ info }}</div> -->
      <el-form :model="loginForm" status-icon :rules="rules" ref="loginForm" label-width="60px" class="demo-loginForm">
        <el-form-item label="账号" prop="username">
          <el-input type="text" v-model="loginForm.username" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input type="password" v-model="loginForm.password" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item class="btn">
          <el-button type="primary" @click="submitForm('loginForm')">登录</el-button>
          <el-button @click="resetForm('loginForm')">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script>
export default {
  name: 'Login',
  data() {
    var validateUser = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入账号'))
      } else {
        callback()
      }
    }
    var validatePass = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入密码'))
      } else {
        callback()
      }
    }
    return {
      loginForm: {
        username: '',
        password: ''
      },
      rules: {
        username: [{ validator: validateUser, trigger: 'blur' }],
        password: [{ validator: validatePass, trigger: 'blur' }]
      }
    }
  },
  methods: {
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          console.log('校验通过', this.loginForm)
          // 如果校验通过，应该请求登录接口-------------
          this.$http.post('/getLogin', this.loginForm).then(({ data: res }) => {
            console.log(res)
            if (res.code === 20000) {
              console.log('请求登录接口成功')
              //登录成功后两步：1. 存储登录信息
              // 1.1 项目中除了登录之外的其他API接口，必须在登录之后才能访问
              // 1.2 token 只应在当前网站打开期间生效，所以将 token 保存在 sessionStorage 中
              window.sessionStorage.setItem('token', res.data.token)
              // 2. 跳转网页
              this.$router.push('/qys')
            } else {
              this.$message.error(res.data.message)
            }
          })
        } else {
          this.$message.warning('必须输入正确信息哦！')
          return false
        }
      })
    },
    resetForm(formName) {
      this.$refs[formName].resetFields()
    }
  }
}
</script>

<style></style>
